package org.example.domain.strategy.service.rule.factory;

import lombok.AllArgsConstructor;
import lombok.Getter;
import org.example.domain.strategy.model.entity.RuleActionEntity;
import org.example.domain.strategy.service.annotation.LogicStrategy;
import org.example.domain.strategy.service.rule.ILogicFilter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: SrmaticHai6532
 * @Create: 2025-07-07-19:18
 * @Description: 规则工厂
 */
@Service
public class DefaultLogicFactory {

    // 定义一个Map，用于存储逻辑过滤器的键值对
    public Map<String, ILogicFilter<?>> logicFilterMap = new ConcurrentHashMap<>();

    // 构造函数，接收一个ILogicFilter类型的列表
    public DefaultLogicFactory(List<ILogicFilter<?>> logicFilters) {
        // 遍历列表中的每一个ILogicFilter
        logicFilters.forEach(logic -> {
            // 获取ILogicFilter的类上的LogicStrategy注解
            LogicStrategy strategy = AnnotationUtils.findAnnotation(logic.getClass(), LogicStrategy.class);
            // 如果注解不为空
            if (null != strategy) {
                // 将注解中的逻辑模式代码作为键，ILogicFilter作为值，存入logicFilterMap中
                logicFilterMap.put(strategy.logicMode().getCode(), logic);
            }
        });
    }

    // 返回logicFilterMap的Map<String, ILogicFilter<T>>类型
    public <T extends RuleActionEntity.RaffleEntity> Map<String, ILogicFilter<T>> openLogicFilter() {
        // 返回logicFilterMap的Map<String, ILogicFilter<T>>类型
        return (Map<String, ILogicFilter<T>>) (Map<?, ?>) logicFilterMap;
    }

    // 定义一个枚举类，用于存储逻辑模式
    @Getter
    @AllArgsConstructor
    public enum LogicModel {

        // 根据抽奖权重返回可抽奖范围KEY
        RULE_WIGHT("rule_weight","【抽奖前规则】根据抽奖权重返回可抽奖范围KEY","before"),
        // 黑名单规则过滤，命中黑名单则直接返回
        RULE_BLACKLIST("rule_blacklist","【抽奖前规则】黑名单规则过滤，命中黑名单则直接返回","before"),
        RULE_LOCK("rule_lock", "【抽奖中规则】抽奖n次后，对应奖品可解锁抽奖", "center"),
        RULE_LUCK_AWARD("rule_luck_award", "【抽奖后规则】抽奖n次后，对应奖品可解锁抽奖", "after"),
        ;

        // 枚举类的属性
        private final String code;
        private final String info;
        private final String type;

        public static boolean isCenter(String code){
            return "center".equals(LogicModel.valueOf(code.toUpperCase()).type);
        }

        public static boolean isAfter(String code){
            return "after".equals(LogicModel.valueOf(code.toUpperCase()).type);
        }

    }
}